package com.demo.word;

import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.model.StylesTable;
import org.apache.poi.xssf.usermodel.DefaultIndexedColorMap;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFColor;

/**
 * @author gy
 * @date 2024/1/2
 */
public class ExcelStyleUtils {
    /**
     * 字体样式
     * @param workbook
     * @return
     */
    public static Font demoFont(Workbook workbook) {
        Font font = workbook.createFont();
        font.setFontName("等线"); // 字体
        font.setFontHeightInPoints((short) 14);// 字号
        font.setBold(true);// 加粗
        font.setColor(IndexedColors.BLACK.getIndex());// 颜色
        font.setItalic(true);// 斜体
        font.setStrikeout(true);// 使用划线
        return font;
    }


    /**
     * 单元格样式
     * @param workbook
     * @return
     */
    public static CellStyle demoStyle(Workbook workbook) {
        CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.setFont(demoFont(workbook)); // 字体
        cellStyle.setAlignment(HorizontalAlignment.CENTER); // 居中
        cellStyle.setWrapText(true); // 自动换行
        cellStyle.setBorderTop(BorderStyle.THIN); // 单元格边框
        cellStyle.setBorderBottom(BorderStyle.THIN); // 单元格边框
        cellStyle.setBorderLeft(BorderStyle.THIN); // 单元格边框
        cellStyle.setBorderRight(BorderStyle.THIN); // 单元格边框
        cellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//高度居中
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND); // 实心填充
//        cellStyle.setFillForegroundColor(new XSSFColor(new Color(181, 230, 181),new DefaultIndexedColorMap()));
        return cellStyle;
    }


    public static void buildStyle(Workbook wb) {
        Sheet sheet;
        Row row;
        for (int s = 0; s < wb.getNumberOfSheets(); s++) { // 遍历Sheet页
            sheet = wb.getSheetAt(s);
            for (int r = sheet.getFirstRowNum(); r <= sheet.getLastRowNum(); r++) { // 遍历所有行
                row = sheet.getRow(r);
                for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) { // 遍历每一样所有单元格
                    if (r == 0) { // 表头
//                        row.getCell(c).setCellStyle(ExcelStyleUtils.headerStyle(wb)); // 设置格式
                        row.getCell(c).setCellStyle(new XSSFCellStyle(new StylesTable())); // 设置格式
                        sheet.autoSizeColumn(c); // 列自动伸缩
                    } else { // 数据
//                        row.getCell(c).setCellStyle(ExcelStyleUtils.cellsStyle(wb)); // 设置格式
                        if (sheet.getColumnWidth(c) > 50 * 256) {
                            sheet.setColumnWidth(c, 50 * 256); // 设置列宽
                        }
                    }
                }
            }
        }
    }

}
